using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IceCS.MiniProfiler.WebApp.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace IceCS.MiniProfiler.WebApp
{
    public class Startup
    {
        public static string SqliteConnectionString { get; } = "Data Source=Samples; Mode=Memory; Cache=Shared";

        private static readonly SqliteConnection TrapConnection = new SqliteConnection(SqliteConnectionString);

        public IConfigurationRoot Configuration { get; }

        public Startup(IWebHostEnvironment env)
        {
            TrapConnection.Open(); //Hold the in-memory SQLite database open

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.WebRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<SampleContext>();
            services.AddMvc(options =>
            {
                // Because the samples have some MyAction and MyActionAsync duplicates
                // See: https://github.com/aspnet/AspNetCore/issues/8998
                options.SuppressAsyncSuffixInActionNames = false;
            });
            services.AddEntityFrameworkSqlite();
            services.AddMiniProfilerInProfile1();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseMiniProfiler();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapAreaControllerRoute("areaRoute", "MySpace",
                       "MySpace/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("default_route", "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapRazorPages();

                endpoints.MapGet("/named-endpoint", async httpContext =>
                {
                    var endpointName = httpContext.GetEndpoint().DisplayName;
                    await httpContext.Response.WriteAsync($"Content from an endpoint named {endpointName}");
                }).WithDisplayName("Named Endpoint");

                endpoints.MapGet("implicitly-named-endpoint", async httpContext =>
                {
                    var endpointName = httpContext.GetEndpoint().DisplayName;
                    await httpContext.Response.WriteAsync($"Content from an endpoint named {endpointName}");
                });
            });

            var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
            using (var serviceScope = serviceScopeFactory.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService<SampleContext>();
                dbContext.Database.EnsureCreated();
            }
            // For nesting test routes
            //new SqliteStorage(SqliteConnectionString).WithSchemaCreation();
        }
    }
}
